// https://preapi.hamster.io/user/ton/wallet/bind?address=UQDCvLQs1N5zZ9HQrHNG30R6ZkXNFi1bXK66oMiXEFTGSNnr


import DexieCtx from '@/utils/dexiectx';
import Config from '@/utils/config';
import { Api, TelegramClient } from 'telegram'
import { StringSession } from 'telegram/sessions'
import HamsterTgweb from './hamster_tgweb'
const stringUtil = require('@/utils/string')
const axiosUitl = require("@/utils/axios");
import { v4 as uuidv4 } from 'uuid';

class HamsterWallet {
    constructor() {
    }

    async bind_tg_wallet_by_phone_number(phone_number) {

        /* request update wallet function */
        // https://preapi.hamster.io/user/ton/wallet/bind?address=UQDCvLQs1N5zZ9HQrHNG30R6ZkXNFi1bXK66oMiXEFTGSNnr




        console.log(phone_number)
        this.dexie = await DexieCtx.db()
        // const allAccounts = await this.dexie.accounts.where("phone").equal(phone_number).toArray()

        const account = await this.dexie.accounts.get({
            phone: phone_number
        })

        const strSession = new StringSession(account.session)
        const client = new TelegramClient(strSession, Config.API_ID, Config.API_HASH, {
            connectionRetries: 3,
            useWSS: true,
            timeout: 20,
        })
        client.phone = phone_number
        const dkweb = new HamsterTgweb()
        dkweb.run(client, this.dexie)
        // invoke the wallet bind function.

        const account_updated = await this.dexie.accounts.get({
            phone: phone_number
        })

        const game_account = await this.dexie.hamster.get({
            phone: phone_number
        })

        const proxy = axiosUitl.parseProxy(account_updated.proxy)
        const axios = axiosUitl.createAxios(proxy)

        const fingerPrint = { "version": "4.2.1", "visitorId": "thevisitoridneedtoreplaced", "components": { "fonts": { "value": ["Agency FB", "Calibri", "Century", "Century Gothic", "Franklin Gothic", "Haettenschweiler", "Leelawadee", "Lucida Bright", "Lucida Sans", "MS Outlook", "MS Reference Specialty", "MS UI Gothic", "MT Extra", "Marlett", "Microsoft Uighur", "Monotype Corsiva", "Pristina", "Segoe UI Light", "SimHei"], "duration": 101 }, "domBlockers": { "duration": 0 }, "fontPreferences": { "value": { "default": 80.6484375, "apple": 80.6484375, "serif": 68, "sans": 80.6484375, "mono": 59.5, "min": 5.046875, "system": 80.6484375 }, "duration": 28 }, "audio": { "value": 0.0000832115, "duration": 68 }, "screenFrame": { "value": [0, 0, 50, 0], "duration": 0 }, "canvas": null, "osCpu": { "duration": 0 }, "languages": { "value": [["zh-CN"]], "duration": 0 }, "colorDepth": { "value": 24, "duration": 0 }, "deviceMemory": { "value": 8, "duration": 0 }, "screenResolution": { "value": [1600, 1000], "duration": 0 }, "hardwareConcurrency": { "value": 20, "duration": 0 }, "timezone": { "value": "Asia/Shanghai", "duration": 8 }, "sessionStorage": { "value": true, "duration": 0 }, "localStorage": { "value": true, "duration": 0 }, "indexedDB": { "value": true, "duration": 0 }, "openDatabase": { "value": false, "duration": 0 }, "cpuClass": { "duration": 0 }, "platform": { "value": "Win32", "duration": 0 }, "plugins": { "value": [{ "name": "PDF Viewer", "description": "Portable Document Format", "mimeTypes": [{ "type": "application/pdf", "suffixes": "pdf" }, { "type": "text/pdf", "suffixes": "pdf" }] }, { "name": "Chrome PDF Viewer", "description": "Portable Document Format", "mimeTypes": [{ "type": "application/pdf", "suffixes": "pdf" }, { "type": "text/pdf", "suffixes": "pdf" }] }, { "name": "Chromium PDF Viewer", "description": "Portable Document Format", "mimeTypes": [{ "type": "application/pdf", "suffixes": "pdf" }, { "type": "text/pdf", "suffixes": "pdf" }] }, { "name": "Microsoft Edge PDF Viewer", "description": "Portable Document Format", "mimeTypes": [{ "type": "application/pdf", "suffixes": "pdf" }, { "type": "text/pdf", "suffixes": "pdf" }] }, { "name": "WebKit built-in PDF", "description": "Portable Document Format", "mimeTypes": [{ "type": "application/pdf", "suffixes": "pdf" }, { "type": "text/pdf", "suffixes": "pdf" }] }], "duration": 0 }, "touchSupport": { "value": { "maxTouchPoints": 0, "touchEvent": false, "touchStart": false }, "duration": 0 }, "vendor": { "value": "Google Inc.", "duration": 0 }, "vendorFlavors": { "value": ["chrome"], "duration": 0 }, "cookiesEnabled": { "value": true, "duration": 1 }, "colorGamut": { "value": "p3", "duration": 0 }, "invertedColors": { "duration": 0 }, "forcedColors": { "value": false, "duration": 0 }, "monochrome": { "value": 0, "duration": 0 }, "contrast": { "value": 0, "duration": 0 }, "reducedMotion": { "value": false, "duration": 0 }, "reducedTransparency": { "value": false, "duration": 0 }, "hdr": { "value": false, "duration": 0 }, "math": { "value": { "acos": 1.4473588658278522, "acosh": 709.889355822726, "acoshPf": 355.291251501643, "asin": 0.12343746096704435, "asinh": 0.881373587019543, "asinhPf": 0.8813735870195429, "atanh": 0.5493061443340548, "atanhPf": 0.5493061443340548, "atan": 0.4636476090008061, "sin": 0.8178819121159085, "sinh": 1.1752011936438014, "sinhPf": 2.534342107873324, "cos": -0.8390715290095377, "cosh": 1.5430806348152437, "coshPf": 1.5430806348152437, "tan": -1.4214488238747245, "tanh": 0.7615941559557649, "tanhPf": 0.7615941559557649, "exp": 2.718281828459045, "expm1": 1.718281828459045, "expm1Pf": 1.718281828459045, "log1p": 2.3978952727983707, "log1pPf": 2.3978952727983707, "powPI": 1.9275814160560204e-50 }, "duration": 0 }, "pdfViewerEnabled": { "value": true, "duration": 0 }, "architecture": { "value": 255, "duration": 0 }, "applePay": { "value": -1, "duration": 0 }, "privateClickMeasurement": { "duration": 0 }, "webGlBasics": { "value": { "version": "WebGL 1.0 (OpenGL ES 2.0 Chromium)", "vendor": "WebKit", "vendorUnmasked": "Google Inc. (Google)", "renderer": "WebKit WebGL", "rendererUnmasked": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)", "shadingLanguageVersion": "WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)" }, "duration": 5 }, "webGlExtensions": null } }


        // 兑换token
        const decoded_url = decodeURIComponent(game_account.tgweb)
        const parsed_url = decoded_url.substring(decoded_url.indexOf("query_id"), decoded_url.indexOf("&tgWebAppVersion"))
        // 替换finterPrint里面的参数，避免被女巫
        fingerPrint.visitorId = uuidv4().replace(new RegExp("-", "gm"), "")
        const reqBody = { "initDataRaw": parsed_url, "fingerprint": fingerPrint };
        // const authRes = await axios.post("https://api.hamsterkombatgame.io/auth/auth-by-telegram-webapp", reqBody);

        let auth_token = "";
        await axios.post('https://api.hamsterkombatgame.io/auth/auth-by-telegram-webapp', reqBody, {
            headers: {}
        }).then(response => {
            auth_token = response.data.authToken
        }).catch(function (error) {
            console.log('>>>>> failed...')
            console.log(error)
        })

        let req_header = await this.get_req_header(auth_token)

        /* 1. Send release bind request */
        await axios.post('https://api.hamsterkombatgame.io/clicker/withdraw/reset', '{}', {
            headers: req_header
        }).then(response => {

        }).catch(function (error) {
            console.log('update failed...')
            console.log(error)
        })

        let update_result = ''


        /* 2. Bind the new wallet address to hamster account, Then check the binding result */
        await axios.post('https://api.hamsterkombatgame.io/clicker/withdraw/set-wallet-as-default', {
            "id": "TonWallet",
            "walletAddress": account_updated.wallet_address
        }, {
            headers: req_header
        }).then(response => {
            update_result = response.data.clickerUser.withdraw.info.TonWallet.depositAddress
        }).catch(function (error) {
            // console.log(error.response.data)
            update_result = error.response.data.error_code
        })

        console.log(update_result)

        await this.dexie.hamster.where("phone").equals(phone_number).modify({
            airdrop_address: update_result,
        })
    }

    async get_req_header(webSessionUrl) {
        const req_header = {
            'content-type': 'application/json',
            Authorization: 'Bearer ' + webSessionUrl
        }

        return req_header
    }
}

export default HamsterWallet